<script lang="ts" setup>
  import { addCompetitionService } from '@/api/competitios'
  import { postData } from '../hooks/postData'
  import { userHook } from '../hooks/user'
  import { useInputTooltip } from '@/hooks/useInputTooltip'
  import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
  import { categoryCP } from '@/types/categoryCp'
  import { fetchAllCategory } from '@/api/category'
  import { Store } from '@/store'
  import { createTipsMessage, uploadTips } from '@/utils/createTipsMessage'
  import { useRouter } from 'vue-router'

  // 定义组件props
  interface Props {
    competitionId?: string | number
    editData?: any // 编辑时的数据，新增时为空
  }
  const props = withDefaults(defineProps<Props>(), {
    competitionId: undefined,
    editData: undefined,
  })
  // 实例化 Store 和 Router
  const store = Store()
  const router = useRouter()
  const { rules, formBase, checkRules, refForm } = postData()
  const { initializeRows, handleInputBlur, handleSelectChange, getFieldError, getRowValidationClass } = userHook(formBase)

  // 使用输入框tooltip hook
  const { registerInput, checkAllTooltips } = useInputTooltip()

  // 注册需要tooltip的输入框
  const {
    inputRef: addressInputRef,
    shouldShow: shouldShowAddressTooltip,
    checkTooltip: checkAddressTooltip,
  } = registerInput('address', () => formBase.value.address || '')
  const {
    inputRef: nameInputRef,
    shouldShow: shouldShowNameTooltip,
    checkTooltip: checkNameTooltip,
  } = registerInput('name', () => formBase.value.name || '')
  const {
    inputRef: organizerInputRef,
    shouldShow: shouldShowOrganizerTooltip,
    checkTooltip: checkOrganizerTooltip,
  } = registerInput('organizer', () => formBase.value.organizer || '')
  const {
    inputRef: conductUnitInputRef,
    shouldShow: shouldShowConductUnitTooltip,
    checkTooltip: checkConductUnitTooltip,
  } = registerInput('conductUnit', () => formBase.value.conductUnit || '')
  const {
    inputRef: descInputRef,
    shouldShow: shouldShowDescTooltip,
    checkTooltip: checkDescTooltip,
  } = registerInput('desc', () => formBase.value.desc || '')

  // 批量监听多个字段变化，统一触发tooltip检查（性能优化）
  watch(
    [
      () => formBase.value.address,
      () => formBase.value.name,
      () => formBase.value.organizer,
      () => formBase.value.conductUnit,
      () => formBase.value.desc,
    ],
    () => {
      // 使用批量检查避免多次单独调用
      checkAllTooltips()
    },
    { flush: 'post' }, // 在DOM更新后触发
  )
  const isEditMode = computed(() => !!props.competitionId)

  const contactDisplayValue = computed(() => {
    if (isEditMode.value) {
      return formBase.value.contact
    } else {
      return store.userName || ''
    }
  })

  const phoneDisplayValue = computed(() => {
    if (isEditMode.value) {
      return formBase.value.phone
    } else {
      return store.userPhone || ''
    }
  })

  // 获取当前竞赛可选择的所属分类
  const users = ref<categoryCP[]>([])

  // 初始化数据
  const initializeData = () => {
    if (isEditMode.value && props.editData) {
      // 编辑模式：使用传入的编辑数据
      Object.assign(formBase.value, props.editData)
    } else {
      // 新增模式：设置默认的负责人信息
      formBase.value.contact = store.userName || ''
      formBase.value.phone = store.userPhone || ''
      formBase.value.instructorId = store.userId
    }
  }

  // 根据表单数据初始化字段状态
  const initializeFieldStates = () => {
    // 初始化竞赛人数字段状态
    if (formBase.value.type === '个人赛') {
      isDisabledNumber.value = true
      rules.number = []
    } else {
      isDisabledNumber.value = false
      rules.number = [
        { required: true, message: '请输入竞赛人数', trigger: 'blur' },
        {
          validator: (rule: any, value: any, callback: any) => {
            if (!/^\d+$/.test(value)) {
              callback(new Error('请输入有效的数字'))
            } else if (value < 1 || value > 1000) {
              callback(new Error('竞赛人数必须在 1 到 1000 之间'))
            } else {
              callback()
            }
          },
          trigger: 'blur',
        },
      ]
    }

    // 初始化交通工具字段状态
    if (formBase.value.shape === '线上') {
      isDisabledTraffic.value = true
      delete rules.traffic
    } else {
      isDisabledTraffic.value = false
      rules.traffic = [{ required: true, message: '请输入交通工具', trigger: 'blur' }]
    }
  }

  onMounted(async () => {
    // 初始化教师表格行数
    initializeRows()
    // 初始化表单数据
    initializeData()
    // 初始化字段状态
    initializeFieldStates()
    // 获取分类数据
    await fetchAllCategory({ departmentId: store.userDepartmentId, status: 2 }).then((res) => {
      users.value = res
    })
  })

  // 注意：组件销毁时tooltip会自动清理，无需手动注销

  // 监听编辑数据变化（用于外部异步加载数据的情况）
  watch(
    () => props.editData,
    (newEditData) => {
      if (newEditData && isEditMode.value) {
        Object.assign(formBase.value, newEditData)
        // 重新初始化字段状态
        nextTick(() => {
          initializeFieldStates()
        })
      }
    },
    { deep: true },
  )
  // 提交进度
  const submitLoading = ref(false)
  // 文件信息上传说明

  const openFileAlert = () => {
    ElMessageBox({
      title: '文件上传详细说明',
      showConfirmButton: false,
      message: createTipsMessage(uploadTips),
    })
  }

  // 临时存储日期范围 - 用于日期组件的双向绑定
  const tempDate = ref<[string, string] | null>(null)
  // 监听 formBase 中的日期变化，同步到 tempDate（用于回显）
  watch(
    () => [formBase.value.startTime, formBase.value.endTime],
    ([startTime, endTime]) => {
      if (startTime && endTime) {
        tempDate.value = [startTime, endTime]
      } else {
        tempDate.value = null
      }
    },
    { immediate: true },
  )

  // 监听 tempDate 变化，同步到 formBase（用于表单提交）
  watch(tempDate, (newVal) => {
    if (newVal && newVal.length === 2) {
      formBase.value.startTime = newVal[0]
      formBase.value.endTime = newVal[1]
    } else {
      formBase.value.startTime = ''
      formBase.value.endTime = ''
    }
  })

  // 控制字段禁用状态
  const isDisabledNumber = ref(false)
  const isDisabledTraffic = ref(false)

  // 监听竞赛类型(个人，团队)变化
  watch(
    () => formBase.value.type,
    (newVal) => {
      if (newVal === '个人赛') {
        // 选择个人赛时，移除竞赛人数的校验规则
        rules.number = []
        refForm.value?.clearValidate(['number'])
        isDisabledNumber.value = true
        formBase.value.number = 1 // 自动设置为 1
      } else {
        // 选择其他赛制时，恢复竞赛人数的校验规则
        isDisabledNumber.value = false
        // 只在新增模式下清空数字，编辑模式保持原值
        if (!isEditMode.value) {
          formBase.value.number = null
        }
        rules.number = [
          { required: true, message: '请输入竞赛人数', trigger: 'blur' },
          {
            validator: (rule: any, value: any, callback: any) => {
              if (!/^\d+$/.test(value)) {
                callback(new Error('请输入有效的数字'))
              } else if (value < 1 || value > 1000) {
                callback(new Error('竞赛人数必须在 1 到 1000 之间'))
              } else {
                callback()
              }
            },
            trigger: 'blur',
          },
        ]
      }
    },
  )

  // 监听竞赛形式变化
  watch(
    () => formBase.value.shape,
    (newVal) => {
      if (newVal === '线上') {
        // 选择线上时，移除交通工具的校验规则
        delete rules.traffic
        refForm.value?.clearValidate(['traffic'])
        isDisabledTraffic.value = true
        formBase.value.traffic = '' // 自动设置为 无
      } else {
        // 选择其他形式时，恢复交通工具的校验规则
        isDisabledTraffic.value = false
        // 只在新增模式下清空交通工具，编辑模式保持原值
        if (!isEditMode.value && !formBase.value.traffic) {
          formBase.value.traffic = ''
        }
        rules.traffic = [{ required: true, message: '请输入交通工具', trigger: 'blur' }]
      }
    },
  )
  // 处理提交事件
  const submit = async () => {
    let loadingInstance = null
    try {
      await checkRules()

      // 显示全屏加载
      loadingInstance = ElLoading.service({
        lock: true,
        text: '正在提交竞赛信息...',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      submitLoading.value = true
      // 确保负责人信息正确设置
      formBase.value.contact = contactDisplayValue.value
      formBase.value.phone = phoneDisplayValue.value
      // 补充完善竞赛负责人所属id
      formBase.value.instructorId ??= store.userId
      await addCompetitionService(formBase.value)
      // 关闭加载
      if (loadingInstance) {
        loadingInstance.close()
        loadingInstance = null
      }
      // 显示成功消息
      ElMessage.success('竞赛信息提交成功')

      // 延迟跳转，让用户看到成功消息
      setTimeout(() => {
        router.push('/competition/my')
      }, 600)
    } catch (error: any) {
      // 关闭加载
      if (loadingInstance) {
        loadingInstance.close()
        loadingInstance = null
      }

      if (error.message !== '表单校验失败') {
        ElMessage.error('竞赛信息提交失败: ' + error.message)
      }
    } finally {
      submitLoading.value = false
    }
  }
</script>
<template>
  <el-form ref="refForm" :model="formBase" :validate-on-rule-change="false" :rules="rules" label-width="80px">
    <!-- 竞赛基本信息 -->
    <div class="panel">
      <h4 class="panel-title">竞赛基本信息</h4>
      <div class="panel-body">
        <el-row type="flex" justify="space-around">
          <el-col :span="7">
            <el-form-item label="竞赛名称" prop="name">
              <el-tooltip :content="formBase.name" placement="top" :disabled="!shouldShowNameTooltip" effect="dark">
                <el-input
                  ref="nameInputRef"
                  v-model.trim="formBase.name"
                  maxlength="80"
                  clearable
                  placeholder="请输入竞赛名称"
                  @input="checkNameTooltip"
                />
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="竞赛形式" prop="shape">
              <tree-select v-model="formBase.shape" dic-code="xfeew"> </tree-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="交通工具" prop="traffic">
              <el-input
                ref="trafficInputRef"
                v-model.trim="formBase.traffic"
                :disabled="isDisabledTraffic"
                clearable
                maxlength="30"
                placeholder="请输入交通工具"
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="竞赛地点" prop="address">
              <el-tooltip :content="formBase.address" placement="top" :disabled="!shouldShowAddressTooltip" effect="dark">
                <el-input
                  ref="addressInputRef"
                  v-model.trim="formBase.address"
                  clearable
                  maxlength="80"
                  placeholder="请输入竞赛地点"
                  @input="checkAddressTooltip"
                />
              </el-tooltip>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 单位，范围，级别 -->
        <el-row type="flex" justify="space-around">
          <el-col :span="7">
            <el-form-item label="承办单位" prop="organizer">
              <el-tooltip :content="formBase.organizer" placement="top" :disabled="!shouldShowOrganizerTooltip" effect="dark">
                <el-input
                  ref="organizerInputRef"
                  v-model.trim="formBase.organizer"
                  clearable
                  maxlength="80"
                  placeholder="请输入校内承办单位"
                  @input="checkOrganizerTooltip"
                />
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="比赛范围" prop="scope">
              <tree-select v-model="formBase.scope" dic-code="code"> </tree-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="竞赛级别" prop="level">
              <el-input v-model.trim="formBase.level" clearable maxlength="10" placeholder="请输入竞赛级别" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="特等奖" prop="special">
              <el-select v-model="formBase.special" placeholder="请选择特等奖情况" clearable>
                <el-option label="是" :value="1" />
                <el-option label="否" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 形式，类型，地点 -->
        <el-row type="flex" justify="space-around">
          <el-col :span="7">
            <el-form-item label="主办单位" prop="conductUnit">
              <el-tooltip :content="formBase.conductUnit" placement="top" :disabled="!shouldShowConductUnitTooltip" effect="dark">
                <el-input
                  ref="conductUnitInputRef"
                  v-model="formBase.conductUnit"
                  maxlength="80"
                  clearable
                  placeholder="请输入主办单位"
                  @input="checkConductUnitTooltip"
                />
              </el-tooltip>
            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item label="竞赛类型" prop="type">
              <tree-select v-model="formBase.type" dic-code="type_code"> </tree-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="竞赛人数" prop="number">
              <el-input v-model="formBase.number" :disabled="isDisabledNumber" clearable placeholder="请输入参赛人数" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="所属分类">
              <select-list
                v-model="formBase.categoryId"
                :options="users"
                label-key="name"
                disabled-key="isDisabled"
                key-field="id"
                placeholder="可选择所属竞赛分类"
                clearable
                :value-on-clear="null"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!--交通工具，人数，时间  -->
        <el-row type="flex" justify="space-around">
          <el-col :span="7">
            <el-form-item label="竞赛日期" prop="startTime">
              <date-time-picker v-model="tempDate" type="datetimerange"></date-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="备注信息">
              <el-tooltip :content="formBase.desc" placement="top" :disabled="!shouldShowDescTooltip" effect="dark">
                <el-input ref="descInputRef" v-model.trim="formBase.desc" placeholder="请输入备注信息" @input="checkDescTooltip" />
              </el-tooltip>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </div>
    <!-- 人员基本信息 -->
    <div class="panel">
      <h4 class="panel-title">人员基本信息</h4>
      <div class="panel-body">
        <el-row type="flex" justify="center" style="gap: 20px">
          <el-col :span="5">
            <el-form-item label="竞赛负责人" label-width="100px">
              <el-input :value="contactDisplayValue" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话">
              <el-input :value="phoneDisplayValue" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 指导教师 -->
        <div class="teacher-info">
          <div class="guide-teacher"> 指导教师信息 </div>
          <!-- 指导教师列表 -->
          <div class="teacher-table-alert">
            <el-table
              border
              :data="formBase.teacher"
              :header-cell-style="{ background: '#f5f5f5', color: '#333' }"
              :row-class-name="getRowValidationClass"
              class="teacher-table"
            >
              <el-table-column align="center" label="姓名" width="180">
                <template #default="scope">
                  <div class="field-wrapper">
                    <el-input v-model.trim="scope.row.name" placeholder="请输入姓名" @blur="handleInputBlur(scope.$index)" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column align="center" label="学历/学位" width="180">
                <template #default="scope">
                  <div class="field-wrapper">
                    <tree-select v-model="scope.row.education" dic-code="res_code" @change="handleSelectChange(scope.$index)"></tree-select>

                    <div v-if="getFieldError(scope.row, scope.$index, 'education')" class="field-error">
                      {{ getFieldError(scope.row, scope.$index, 'education') }}
                    </div>
                  </div>
                </template>
              </el-table-column>

              <el-table-column align="center" label="职称" width="180">
                <template #default="scope">
                  <div class="field-wrapper">
                    <tree-select
                      v-model="scope.row.title"
                      dic-code="positional_code"
                      @change="handleSelectChange(scope.$index)"
                    ></tree-select>
                    <div v-if="getFieldError(scope.row, scope.$index, 'title')" class="field-error">
                      {{ getFieldError(scope.row, scope.$index, 'title') }}
                    </div>
                  </div>
                </template>
              </el-table-column>

              <el-table-column align="center" label="所在教学单位">
                <template #default="scope">
                  <div class="field-wrapper">
                    <el-input v-model.trim="scope.row.department" placeholder="请输入所在单位" @blur="handleInputBlur(scope.$index)" />
                  </div>
                </template>
              </el-table-column>

              <el-table-column align="center" label="备注">
                <template #default="scope">
                  <div class="field-wrapper">
                    <el-input v-model.trim="scope.row.remarks" placeholder="备注信息" @blur="handleInputBlur(scope.$index)" />
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <el-alert title="指导教师按贡献大小顺序填写" type="success" :closable="false" center show-icon class="el-icon-s-opportunity">
              <template #icon>
                <Bell />
              </template>
            </el-alert>
          </div>
        </div>
      </div>
    </div>
    <div class="panel">
      <h4 class="panel-title">具体信息</h4>
      <div class="panel-body">
        <!-- 竞赛实施方案 -->
        <el-row type="flex" justify="space-around">
          <el-col :span="21">
            <el-form-item label="竞赛实施方案" prop="plan" label-width="140px">
              <el-input
                v-model="formBase.plan"
                maxlength="200"
                type="textarea"
                :autosize="{ minRows: 10, maxRows: 20 }"
                placeholder="（包括竞赛的主要内容、举办方式、拟组队情况、赛前培训情况、所需条件、安全措施等）"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 上届使用情况 -->
        <el-row type="flex" justify="space-around">
          <el-col :span="21">
            <el-form-item label="上届竞赛获奖情况及经费使用情况" prop="cost" label-width="140px">
              <el-input v-model="formBase.cost" maxlength="200" type="textarea" :autosize="{ minRows: 5, maxRows: 10 }" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 竞赛预算 -->
        <el-row type="flex" justify="space-around">
          <el-col :span="21">
            <el-form-item label="竞赛预算" prop="budget" label-width="140px">
              <el-input
                v-model="formBase.budget"
                maxlength="200"
                type="textarea"
                :autosize="{ minRows: 10, maxRows: 20 }"
                placeholder="（与竞赛密切相关的报名、组织宣传、图书资料、元器件消耗、实物制作材料、培训辅导、外出参加竞赛期间师生交通差旅及集训补贴等详细计算费用）"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="panel">
      <h4 class="panel-title"
        >附件信息<el-icon style="cursor: pointer" @click="openFileAlert"><QuestionFilled /></el-icon
      ></h4>
      <div class="panel-body fileList">
        <el-form-item prop="fileLists">
          <file-upload
            v-model="formBase.fileLists"
            provider="qcloud"
            :limit="2"
            accept=".zip, .pdf, .docx"
            :auto-upload="false"
          ></file-upload>
        </el-form-item>
      </div>
    </div>
  </el-form>
  <div class="btn">
    <el-button type="primary" @click="submit">提交</el-button>
    <el-button>暂存</el-button>
    <el-button>取消</el-button>
  </div>
</template>
<style scoped lang="scss">
  :deep(.el-table .row-incomplete) {
    background-color: #fef0f0 !important;
  }

  :deep(.el-table .row-incomplete td) {
    background-color: #fef0f0 !important;
  }
  .teacher-info {
    display: flex;
    gap: 16px;
    padding: 0 20px;
    .teacher-table-alert {
      width: 100%;
      display: flex;
      // 侧轴为主轴
      flex-direction: column;
      gap: 16px;
      padding-bottom: 10px;
    }
    .guide-teacher {
      width: 20%;
      font-weight: bold;
      text-align: center;
      letter-spacing: 10px;
      border-right: 2px dashed #ccc;
      writing-mode: vertical-rl;
      text-orientation: upright;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .teacher-table {
      flex: 1;
      width: 100%;
    }
    .admin-teacher-input {
      margin-top: 20px;
    }
  }

  /* 字段包装器 */
  .field-wrapper {
    position: relative;
    padding: 4px;
  }

  /* 错误状态的输入框 */
  .has-error :deep(.el-input__wrapper) {
    border-color: #f56c6c !important;
    box-shadow: 0 0 0 1px #f56c6c inset;
  }

  .has-error :deep(.el-select .el-input__wrapper) {
    border-color: #f56c6c !important;
    box-shadow: 0 0 0 1px #f56c6c inset;
  }

  /* 自定义错误提示样式 */
  .field-error {
    color: #f56c6c;
    font-size: 12px;
    line-height: 1;
    padding-top: 4px;
    text-align: left;
    margin: 0;
  }

  /* 确保表格行高度能容纳错误信息 */
  :deep(.el-table td) {
    padding: 8px 0;
    vertical-align: top;
  }
  :deep(.el-date-editor .el-range-input) {
    font-size: 11px;
  }
  :deep(.el-table .el-table__cell) {
    padding: 8px 0;
    vertical-align: top;
  }
  .fileList {
    height: 200px;
    padding: 0 20px;
  }
  .btn {
    width: 30%;
    margin: 40px auto;
    display: flex;
    justify-content: space-around;
  }
</style>
